package com.gexiaobao.pigeon.ui.fragment.mine.organization

import android.annotation.SuppressLint
import android.content.res.ColorStateList
import android.os.Bundle
import android.view.View
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.eventViewModel
import com.gexiaobao.pigeon.app.model.bean.OrgInfoDetailResponse
import com.gexiaobao.pigeon.app.model.param.FollowOrgParams
import com.gexiaobao.pigeon.app.util.ImageLoaderManager
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.databinding.ActivityPigeonShedInfoBinding
import com.gexiaobao.pigeon.ui.fragment.mine.organization.detail.FragmentIntroduction
import com.gexiaobao.pigeon.ui.fragment.mine.organization.detail.FragmentOrgCompetition
import com.gexiaobao.pigeon.ui.fragment.mine.organization.detail.FragmentShedNotice
import com.gexiaobao.pigeon.viewmodel.OrgDetailViewModel
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayout.OnTabSelectedListener
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import kotlin.math.abs

/**
 * @Author      : hxw
 * @Date        : 2024/5/22 17:44
 * @Describe    : 公棚详情页面
 */
class FragmentPigeonShedInfo : BaseFragment<OrgDetailViewModel, ActivityPigeonShedInfoBinding>(), AppBarLayout.OnOffsetChangedListener,
    FragmentOrgCompetition.OnDataSendListener {

    private var orgIcon: String = ""
    private var type: String = ""
    private var mRaceName: String = ""
    private var orgDescribe: String = ""
    private var isFollow = false
    private var mCarState = false
    private var mOrgId = 0
    private var mRaceId = 0

    private var childFragment3: FragmentIntroduction? = null

    override fun initView(savedInstanceState: Bundle?) {
        setStatusBarTranslucent()
        mDatabind.appBar.addOnOffsetChangedListener(this)
        mOrgId = requireArguments().getInt("orgId", 0)
        type = requireArguments().getString("type").toString()
        if (type == "race") {
            mRaceName = requireArguments().getString("raceName").toString()
            mRaceId = requireArguments().getInt("raceId", 0)
        }
        initTabLayout()

        /** tabLayout去除点击背景 */
        mDatabind.tabCollect.tabRippleColor = ColorStateList.valueOf(ContextCompat.getColor(requireContext(), android.R.color.transparent))

        eventViewModel.toNotifyRaceName.observeInFragment(this) {
            mRaceName = it
            mDatabind.tvOrgRaceName.text = it
            mDatabind.tvOrgDetailTitle.text = it
        }
    }

    private fun setFollowStatus(isFollow: Boolean) {
        if (isFollow) {
            mDatabind.tvOrgFollow.text = getString(R.string.followed)
            mDatabind.ivOrgFollow.isVisible = false
            mDatabind.llOrgFollow.background = ContextCompat.getDrawable(requireContext(), R.drawable.round_btn_blue5_bg)
            mDatabind.tvOrgFollow.setTextColor(ContextCompat.getColor(requireContext(), R.color.white))
        } else {
            mDatabind.tvOrgFollow.text = getString(R.string.follow)
            mDatabind.ivOrgFollow.isVisible = true
            mDatabind.llOrgFollow.background = ContextCompat.getDrawable(requireContext(), R.drawable.round_btn_5a5a5a_5radiu_bg)
            mDatabind.tvOrgFollow.setTextColor(ContextCompat.getColor(requireContext(), R.color.white))
        }
    }

    private fun initTabLayout() {
        val tab1 = mDatabind.tabCollect.newTab().setText(getString(R.string.Competition))
        mDatabind.tabCollect.addTab(tab1)
        val tab2 = mDatabind.tabCollect.newTab().setText(getString(R.string.announcement))
        mDatabind.tabCollect.addTab(tab2)
        val tab3 = mDatabind.tabCollect.newTab().setText(getString(R.string.agency))
        mDatabind.tabCollect.addTab(tab3)
//        val tab4 = mDatabind.tabCollect.newTab().setText(getString(R.string.auction))
//        mDatabind.tabCollect.addTab(tab4)

        mDatabind.tabCollect.addOnTabSelectedListener(object : OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                replaceFragments(tab!!.position)
                mDatabind.tvOrgInfoHistoryRace.isVisible = tab.position == 0
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {}
            override fun onTabReselected(tab: TabLayout.Tab?) {}
        })
        replaceFragments(0)
    }

    private fun replaceFragments(position: Int) {
        childFragment3 = FragmentIntroduction.newInstance(mOrgId)
        childFragmentManager.beginTransaction().apply {
            when (position) {
                0 -> replace(R.id.OrgInfoContainer, FragmentOrgCompetition.newInstance(mRaceId, mOrgId, type, mRaceName))
                1 -> replace(R.id.OrgInfoContainer, FragmentShedNotice.newInstance(mRaceId, mOrgId, mRaceName, orgDescribe))
                2 -> replace(R.id.OrgInfoContainer, childFragment3!!)
//                3 -> replace(R.id.OrgInfoContainer, FragmentAuction.newInstance())
            }
        }.commitAllowingStateLoss()
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(
            mDatabind.ivDetailBack,
            mDatabind.image,
            mDatabind.llOrgFollow,
            mDatabind.tvOrgInfoHistoryRace,
        ) {
            when (it) {
                mDatabind.tvOrgInfoHistoryRace -> {
                    nav().navigateAction(R.id.action_to_history_match, Bundle().apply {
                        putString("orgId", mOrgId.toString())
                    })
                }

                mDatabind.image -> openBigImage(mDatabind.image, orgIcon)
                mDatabind.ivDetailBack -> nav().navigateUp()

                mDatabind.llOrgFollow -> {
                    val body = FollowOrgParams(
                        orgId = mOrgId
                    )
                    if (isFollow) {
                        mViewModel.cancelFollowing(body)
                    } else {
                        mViewModel.followOrg(body)
                    }
                }
            }
        }
    }

    @SuppressLint("SuspiciousIndentation")
    override fun createObserver() {
        super.createObserver()
        /** 关注组织 */
        mViewModel.followOrgResult.observe(viewLifecycleOwner) {
            if (it.isSuccess) {
                isFollow = true
                setFollowStatus(true)
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
        /** 取消关注组织 */
        mViewModel.cancelFollowOrgResult.observe(viewLifecycleOwner) {
            if (it.isSuccess) {
                isFollow = false
                setFollowStatus(false)
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
    }

    override fun onOffsetChanged(appBarLayout: AppBarLayout?, verticalOffset: Int) {
        val absVerticalOffset = abs(verticalOffset)//AppBarLayout竖直方向偏移距离px
        val totalScrollRange = appBarLayout?.totalScrollRange//AppBarLayout总的距离px

        if (totalScrollRange != null) {
            if (absVerticalOffset <= totalScrollRange * 0.4) {
                mDatabind.tvOrgDetailTitle.visibility = View.GONE
                mDatabind.conLayoutTitle.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.comm_transparent))
            } else if (absVerticalOffset >= totalScrollRange * 0.7) {
                mDatabind.tvOrgDetailTitle.visibility = View.VISIBLE
                mDatabind.conLayoutTitle.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_99CCFF))
            }
        }
    }

    // 父 Fragment 提供一个方法来传递数据给子 Fragment B
    fun passDataToChildFragment(data: OrgInfoDetailResponse) {
        childFragment3?.receiveData(data)
    }

    override fun onMessageSent(data: OrgInfoDetailResponse) {
        mDatabind.data = data
        orgIcon = data.icon
        isFollow = data.followState
        setFollowStatus(isFollow)
        ImageLoaderManager.loadCircleImageFall(requireContext(), orgIcon, mDatabind.image, R.mipmap.profilepic_str_1)
        mRaceName = if (type == "race") {
            requireArguments().getString("raceName").toString()
        } else {
            data.raceName
        }
        mCarState = data.isTransport
        orgDescribe = data.desc
        mDatabind.tvOrgRaceName.text = mRaceName
        mDatabind.tvOrgDetailTitle.text = mRaceName
    }
}